<?php

namespace app\uniapp\controller;


use app\model\store\OrderRefund;
use app\uniapp\middleware\CheckLogin;
use app\uniapp\service\OrderRefundService;
use app\uniapp\service\UniAuthService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;

class OrderRefundController extends UniController
{

    protected array $middleware = [
        CheckLogin::class,
    ];

    public function paginate(): Json
    {
        $where = [
            ['user_id', '=', UniAuthService::instance()->getLoginId()],
        ];
        $status = $this->param('audit_status', "");

        if ($status !== ""){
            $where[] = ['audit_status', '=', $status];
        }
        $list = OrderRefundService::instance()->setWhere($where)->paginate(20);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function find(): Json
    {
        $id = $this->param('id');
        $info = OrderRefundService::instance()->setPkWhere($id)->find();
        return jsonSuccess([
            'info' => $info,
        ]);
    }

    /**
     * 退货单发货
     * @return Json
     */
    public function delivery(): Json
    {
        $post = $this->post();
        try {
            validate([
                'id' => 'require',
                'express_order_no' => 'require'
            ], [
                'id' => '缺少售后单',
                'express_order_no' => '缺少快递单号'
            ])->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonError($e->getError());
        }

        OrderRefund::update($post);

        return  jsonSuccess();

    }

}
